//
//  GoOutViewController.m
//  ArtOfLiving
//
//  Created by 刘虎 on 16/4/29.
//  Copyright © 2016年 刘虎. All rights reserved.
//

#import "GoOutViewController.h"
#import "GoOutHotTableView.h"
#import "GoOutAcePackCollectionView.h"
#import "GoOutDestinationTableView.h"

#import "GoOutMainheadViewModel.h"
#import "TravelNotesModel.h"
#import "GoOutAcePackTopicModel.h"
#import "GoOutAcePackTopicTitleModel.h"

@interface GoOutViewController ()<UIScrollViewDelegate, DWBubbleMenuViewDelegate>

@property (nonatomic, strong) NSMutableArray *headViewDataSourceMArr;               //头饰图数据
@property (nonatomic, strong) NSMutableArray *travelNotesDataSourceMArr;            //游记数据
@property (nonatomic, strong) NSMutableArray *acePackTopicTitleMArr;                     //锦囊标题数据
@property (nonatomic, strong) NSMutableDictionary *acePackTopicDetailMDic;          //锦囊专题数据

@property (nonatomic, strong) NSMutableDictionary *parameters;                      //请求参数
@property (nonatomic, strong) UIScrollView *scrollView;                             //底部滚动视图
@property (nonatomic, assign) NSInteger acePackIndex;                               //记录点击的锦囊的下标

@property (nonatomic, strong) DWBubbleMenuButton *bubbleMenuView;                    //地区选择菜单
@property (nonatomic, strong) LHSelectedNavigationViewTools *selectedNavigationView;//顶部导航标记
@property (nonatomic, strong) GoOutHotTableView *hotTableView;                      //热门游记
@property (nonatomic, strong) GoOutAcePackCollectionView *acePackCollectionView;    //随身锦囊
@property (nonatomic, strong) GoOutDestinationTableView *destinationTableView;      //目的地


@end

@implementation GoOutViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.acePackIndex = 0;
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.tabBarController.hidesBottomBarWhenPushed = YES;
    
    [self.view addSubview:self.selectedNavigationView];
    
    [self.scrollView addSubview:self.hotTableView];
    [self.scrollView addSubview:self.acePackCollectionView];
    [self.scrollView addSubview:self.destinationTableView];
    
    [self loadDataFromNet];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
}

- (void)didReceiveMemoryWarning {
    
    [super didReceiveMemoryWarning];
}


#pragma mark - -----scrollView的代理方法-----
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    if ([scrollView isEqual:self.scrollView]) {
        
        [self.selectedNavigationView moveMarkLabelWithContentOffset:scrollView.contentOffset];
        if (scrollView.contentOffset.x == kScreenWidth) {//请求随身锦囊 最新锦囊数据
            
            if (self.acePackTopicTitleMArr.count == 0) {//如果已经请求过就不在请求
                
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    
                    [self fetchDataSourceWithUrlString:kAcePackTopicTitleAll parameter:self.parameters];
                    while (self.acePackTopicTitleMArr.count == 0) {
                        
                    }
                    [self fetchDataSourceWithUrlString:kAcePackTopic parameter:self.parameters];
                });
            }
        } else if (self.scrollView.contentOffset.x == 2*kScreenWidth) {//请求目的地数据
            
            
            
        }
    }
}


#pragma mark - -----数据------

- (void)loadDataFromNet {

//    dispatch_queue_t serialQueue = dispatch_queue_create("serialQueue", DISPATCH_QUEUE_SERIAL);
//    dispatch_async(serialQueue, ^{
//        
//        [self fetchDataSourceWithUrlString:kGoOutMainList parameter:self.parameters];
//        [self fetchDataSourceWithUrlString:kTravelNotes parameter:self.parameters];
//    });
    
    
//    NSBlockOperation *blockOperation = [NSBlockOperation blockOperationWithBlock:^{
//        
//        [self fetchDataSourceWithUrlString:kGoOutMainList parameter:self.parameters];
//        [self fetchDataSourceWithUrlString:kTravelNotes parameter:self.parameters];
//    }];
//    blockOperation.completionBlock = ^(){
//       
//        [self fetchDataSourceWithUrlString:kTravelNotes parameter:self.parameters];
//    };
//    [blockOperation start];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        [self fetchDataSourceWithUrlString:kGoOutMainList parameter:self.parameters];
        while (self.headViewDataSourceMArr.count == 0) {
            
        }
        [self fetchDataSourceWithUrlString:kTravelNotes parameter:self.parameters];
    });
    
}

- (void)fetchDataSourceWithUrlString:(NSString *)urlString parameter:(NSMutableDictionary *)parameter {
    
    [LHDataRequestTools getFetchDataWithUrlString:urlString paramenters:parameter success:^(id data) {
        
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        
        if ([urlString isEqualToString:kTravelNotes]) {//游记数据
            
            for (NSDictionary *dic in resultDic[@"data"]) {
                
                TravelNotesModel *model = [[TravelNotesModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.travelNotesDataSourceMArr addObject:model];
            }
            if ([self.hotTableView.mj_header isRefreshing]) {
                
                [self.travelNotesDataSourceMArr removeObjectsInRange:NSMakeRange(0, self.travelNotesDataSourceMArr.count-10)];
            }
            self.hotTableView.travelNotesDataSourceMArr = self.travelNotesDataSourceMArr;
            [self.hotTableView reloadData];
            [self.hotTableView.mj_footer endRefreshing];
            [self.hotTableView.mj_header endRefreshing];
        } else if ([urlString isEqualToString:kGoOutMainList]) {//说走就走头视图数据
            
            NSLog(@"%@", resultDic[@"info"]);
            for (NSDictionary *dic in resultDic[@"data"][@"subject"]) {
                
                GoOutMainheadViewModel *model = [[GoOutMainheadViewModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.headViewDataSourceMArr addObject:model];
            }
            if ([self.hotTableView.mj_header isRefreshing]) {
                
                [self.headViewDataSourceMArr removeObjectsInRange:NSMakeRange(0, self.headViewDataSourceMArr.count-3)];
            }
            self.hotTableView.headViewDataSourceMArr = self.headViewDataSourceMArr;
            [self.hotTableView creatTableHeadView];
        } else if ([urlString isEqualToString:kAcePackTopicTitleAll]) {//锦囊标题数据
            
            for (NSDictionary *dic in resultDic[@"data"]) {
                
                GoOutAcePackTopicTitleModel *model = [[GoOutAcePackTopicTitleModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.acePackTopicTitleMArr addObject:model];
            }
            [self createBubbleMenu];
        } else if ([urlString isEqualToString:kAcePackTopic]) {//锦囊专题数据
            
            NSMutableArray *tempArr = [[NSMutableArray alloc] init];
            for (NSDictionary *countryDic in resultDic[@"data"]) {
                
                for (NSDictionary *dic in countryDic[@"guides"]) {
                    
                    GoOutAcePackTopicModel *model = [[GoOutAcePackTopicModel alloc] init];
                    [model setValuesForKeysWithDictionary:dic];
                    [tempArr addObject:model];
                }
            }
            GoOutAcePackTopicTitleModel *model = self.acePackTopicTitleMArr[self.acePackIndex];
            [self.acePackTopicDetailMDic setObject:tempArr forKey:model.cnname];
            self.acePackCollectionView.dataSourceMArr = tempArr;
            [self.acePackCollectionView reloadData];
        }
        
    } fail:^{
        
        NSLog(@"旅行主界面请求数据失败");
    } view:[self.hotTableView.mj_header isRefreshing]?nil:self.view];
        
}

#pragma mark - -----选择地区菜单------
- (void)createBubbleMenu {
    
    NSMutableArray *buttonsMArr = [[NSMutableArray alloc] init];
    for (int i = 0; i < self.acePackTopicTitleMArr.count; i++) {
        
        GoOutAcePackTopicTitleModel *model = self.acePackTopicTitleMArr[i];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [button setTitle:[model.cnname substringToIndex:2] forState:UIControlStateNormal];
        button.frame = CGRectMake(0.0f, 0.0f, 30.0f, 30.0f);
        button.layer.cornerRadius = button.frame.size.height / 2.0f;
        button.backgroundColor = [UIColor colorWithRed:1.0f green:0.0f blue:0.0f alpha:0.6f];
        button.clipsToBounds = YES;
        button.tag = 100 + i;
        [button addTarget:self action:@selector(bubbleMenuViewBtnClickedAction:) forControlEvents:UIControlEventTouchUpInside];
        [buttonsMArr addObject:button];
    }
    [self.bubbleMenuView addButtons:buttonsMArr];
}

- (void)bubbleMenuViewBtnClickedAction:(UIButton *)sender {
    
    GoOutAcePackTopicTitleModel *model = self.acePackTopicTitleMArr[sender.tag-100];
    NSArray *tempArr = [self.acePackTopicDetailMDic objectForKey:model.cnname];
    if (tempArr.count == 0) {//没有请求过数据
        
        [self.parameters setValue:model.ID forKey:@"id"];
        [self fetchDataSourceWithUrlString:kAcePackTopic parameter:self.parameters];
    } else {//已经请求过数据
        
        self.acePackCollectionView.dataSourceMArr = [tempArr mutableCopy];
        [self.acePackCollectionView reloadData];
    }
}

- (void)bubbleMenuButtonWillExpand:(DWBubbleMenuButton *)expandableView {
    
    UIView *blurredView = [[UIView alloc] initWithFrame:CGRectMake(kScreenWidth, 0, kScreenWidth, self.scrollView.frame.size.height)];
    blurredView.backgroundColor = [UIColor blackColor];
    blurredView.alpha = 0.5f;
    blurredView.tag = 10000;
    UITapGestureRecognizer *removeBlurredGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removeBlurredView:)];
    [blurredView addGestureRecognizer:removeBlurredGesture];
    [self.scrollView insertSubview:blurredView belowSubview:expandableView];
}

- (void)removeBlurredView:(UITapGestureRecognizer *)sender {
    
    [self.bubbleMenuView dismissButtons];
}

- (void)bubbleMenuButtonWillCollapse:(DWBubbleMenuButton *)expandableView {
    
    UIView *blurredView = [self.view viewWithTag:10000];
    [blurredView removeFromSuperview];
}

#pragma mark - -----属性的懒加载------
- (NSMutableDictionary *)parameters {
    
    if (!_parameters) {
        
        _parameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"qyer_ios", @"client_id",@"cd254439208ab658ddf9", @"client_secret", @10, @"count", @1, @"page", @"40.03623104039519", @"lat", @"116.3638251674019", @"lon", @"App%2520Store",@"track_app_channel", @6.8, @"track_app_version", @"iPhone7%2C1", @"track_device_info", @"7B6FA080-F9FB-44C1-B932-401CD69CD5D2", @"track_deviceid", @"ios%25209.1", @"track_os", @"index", @"type", @1, @"v", @999999, @"id", nil];
    }
    return _parameters;
}

- (NSMutableArray *)headViewDataSourceMArr {
    
    if (!_headViewDataSourceMArr) {
        
        _headViewDataSourceMArr = [[NSMutableArray alloc] init];
    }
    return _headViewDataSourceMArr;
}

- (NSMutableArray *)travelNotesDataSourceMArr {
    
    if (!_travelNotesDataSourceMArr) {
        
        _travelNotesDataSourceMArr = [[NSMutableArray alloc] init];
    }
    return _travelNotesDataSourceMArr;
}

- (NSMutableArray *)acePackTopicTitleMArr {
    
    if (!_acePackTopicTitleMArr) {
        
        _acePackTopicTitleMArr = [[NSMutableArray alloc] init];
    }
    return _acePackTopicTitleMArr;
}

- (NSMutableDictionary *)acePackTopicDetailMDic {
    
    if (!_acePackTopicDetailMDic) {
        
        _acePackTopicDetailMDic = [[NSMutableDictionary alloc] init];
    }
    return _acePackTopicDetailMDic;
}

- (UIScrollView *)scrollView {
    
    if (!_scrollView) {
        
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 94, kScreenWidth, kScreenHeight-64-49-30)];
        _scrollView.contentSize = CGSizeMake(kScreenWidth*3, kScreenHeight-64-49-30);
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.bounces = NO;
        _scrollView.pagingEnabled = YES;
        _scrollView.delegate = self;
        [self.view addSubview:_scrollView];
    }
    return _scrollView;
}

- (LHSelectedNavigationViewTools *)selectedNavigationView {
    
    if (!_selectedNavigationView) {
        
        _selectedNavigationView = [[LHSelectedNavigationViewTools alloc] initLHSelectedNavigationViewToolsWithFrame:CGRectMake(0, 64, kScreenWidth, 30) ButtonTitle:[[NSArray alloc] initWithObjects:@"说走就走", @"随身锦囊", @"目的地", nil]];
        __block GoOutViewController *blockSelf = self;
        _selectedNavigationView.selectedScrollViewPageBlock = ^(NSInteger index) {
            
            CGPoint point = blockSelf.scrollView.contentOffset;
            point.x = kScreenWidth * index;
            blockSelf.scrollView.contentOffset = point;
        };
    }
    return _selectedNavigationView;
}


- (DWBubbleMenuButton *)bubbleMenuView {
    
    if (!_bubbleMenuView) {
        
        _bubbleMenuView = [[DWBubbleMenuButton alloc] initWithFrame:CGRectMake(kScreenWidth*2-60.0, self.scrollView.frame.size.height-60.0, 40, 40) expansionDirection:DirectionUp];
        UILabel *homeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 40, 40)];
        homeLabel.text = @"Tap";
        homeLabel.textColor = [UIColor whiteColor];
        homeLabel.textAlignment = NSTextAlignmentCenter;
        homeLabel.layer.cornerRadius = homeLabel.frame.size.height / 2.f;
        homeLabel.backgroundColor = [UIColor redColor];
        homeLabel.clipsToBounds = YES;
        _bubbleMenuView.homeButtonView = homeLabel;
        _bubbleMenuView.delegate = self;
        [self.scrollView addSubview:_bubbleMenuView];
    }
    [self.scrollView bringSubviewToFront:_bubbleMenuView];
    return _bubbleMenuView;
}

- (GoOutHotTableView *)hotTableView {
    
    if (!_hotTableView) {
        
        _hotTableView = [[GoOutHotTableView alloc] initWithFrame:CGRectMake(0, 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height) style:UITableViewStylePlain];
        _hotTableView.navC = self.navigationController;
        _hotTableView.mj_footer = [MJRefreshBackFooter footerWithRefreshingBlock:^{
            
            NSInteger page = [[self.parameters objectForKey:@"page"] integerValue];
            page += 1;
            [self.parameters setObject:[NSNumber numberWithInteger:page] forKey:@"page"];
            [self fetchDataSourceWithUrlString:kTravelNotes parameter:self.parameters];
        }];
        _hotTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            
            [self loadDataFromNet];
        }];
    }
    return _hotTableView;
}

- (GoOutAcePackCollectionView *)acePackCollectionView {
    
    if (!_acePackCollectionView) {
        
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.itemSize = CGSizeMake((kScreenWidth-20.0)/3.0f, (5.0/3.0)*(kScreenWidth-30.0)/3.0f);
        layout.minimumLineSpacing = 5.0;
        layout.minimumInteritemSpacing = 5.0;
        layout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
        _acePackCollectionView = [[GoOutAcePackCollectionView alloc] initWithFrame:CGRectMake(self.scrollView.frame.size.width, 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height) collectionViewLayout:layout];
        _acePackCollectionView.navC = self.navigationController;
    }
    return _acePackCollectionView;
}

- (GoOutDestinationTableView *)destinationTableView {
    
    if (!_destinationTableView) {
        
        _destinationTableView = [[GoOutDestinationTableView alloc] initWithFrame:CGRectMake(self.scrollView.frame.size.width*2, 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height) style:UITableViewStylePlain];

    }
    return _destinationTableView;
}

@end
